package com.sunlg.smarthome.contract.presenter;

import com.sunlg.smarthome.base.App;
import com.sunlg.smarthome.base.C;
import com.sunlg.smarthome.contract.UpdateUserContract;
import com.sunlg.smarthome.data.entity.User;
import com.sunlg.smarthome.data.remote.MySubscriber;
import com.sunlg.smarthome.data.remote.Result;
import com.sunlg.smarthome.data.remote.SHServiceWrapper;
import com.sunlg.smarthome.utils.PreferHelper;

/**
 * Created by sunlg on 2017/5/30.
 */

public class UpdateUserPresenter implements UpdateUserContract.Presenter {

    private UpdateUserContract.View mView;
    private SHServiceWrapper mSHServiceWrapper;
    private PreferHelper preferHelper;

    public UpdateUserPresenter() {
        mSHServiceWrapper = App.getInstance().getServiceWrapper();
        preferHelper = App.getInstance().getPreferHelper();
    }

    @Override
    public void updateUser(final User user) {
        mSHServiceWrapper.updateUser(user,
                new MySubscriber<Result<User>>() {
                    @Override
                    public void onSuccess(Result<User> data) {
                        if(data.getCode() == C.ActionStatus.SUCCESS){
                            User u = data.getData();
                            mView.updateSuccess(u);
                            if(u != null) {
                                preferHelper.setInt(C.PreKey.USER_ID, u.getId());
                                preferHelper.setString(C.PreKey.USER_NAME, u.getUsername());
                                preferHelper.setString(C.PreKey.EMAIL, u.getEmail());
                                preferHelper.setString(C.PreKey.PHONE, u.getPhone());
                            }
                            if(preferHelper.getBoolean(C.PreKey.IS_REMEMBER, false)){
                                preferHelper.setString(C.PreKey.PASSWORD, user.getPassword());
                            }
                        }else {
                            _onError(new Throwable(data.getMsg()));
                        }
                    }

                    @Override
                    public void _onError(Throwable e) {
                        mView.showError(e.getMessage());
                    }
                });
    }

    @Override
    public void attachView(UpdateUserContract.View view) {
        mView = view;
    }

    @Override
    public void dettachView() {
        mView = null;
    }
}
